package com.lemon.system.service.impl;

import com.lemon.core.web.Result;
import com.lemon.mybatisplus.base.BaseServiceImpl;
import com.lemon.mybatisplus.enums.DeleteEnum;
import com.lemon.mybatisplus.enums.StatusEnum;
import com.lemon.redis.service.RedisService;
import com.lemon.security.properties.JwtConfigProperties;
import com.lemon.security.dto.LoginUserDetail;
import com.lemon.system.dao.UserDAO;
import com.lemon.system.dto.UserDTO;
import com.lemon.system.po.UserPO;
import com.lemon.system.service.IMenuResourceService;
import com.lemon.system.service.IUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户表 业务实现类
 *
 * @author 李猛
 * @since 2024-02-11
 */
@Log4j2
@Service
public class UserServiceImpl extends BaseServiceImpl<UserDAO, UserPO, UserDTO> implements IUserService {
    @Resource
    private RedisService redisService;
    @Resource
    private IMenuResourceService iMenuResourceService;
    @Resource
    private JwtConfigProperties properties;

    @Override
    public Result<Void> getByUsername(String username) {
        //1.查询用户信息
        Map<String,Object> param = new HashMap<>();
        param.put("username",username);
        param.put(StatusEnum.ENABLE.getColumn(), StatusEnum.ENABLE.getValue());
        param.put(DeleteEnum.UNABLE.getColumn(), DeleteEnum.UNABLE.getValue());
        List<LoginUserDetail> loginUserDetailList = this.baseMapper.getByUsername(param);
        if (CollectionUtils.isEmpty(loginUserDetailList) || loginUserDetailList.size() != 1) {
            return Result.fail("用户名错误或租户信息异常！");
        }
        LoginUserDetail loginUserDetail = loginUserDetailList.get(0);

        //2.获取对应的权限
        List<String> resourceList = iMenuResourceService.getResourceByUserId(loginUserDetail.getUserId(), loginUserDetail.getTenantId());
        if (!CollectionUtils.isEmpty(resourceList)) {
            loginUserDetail.setResourceList(resourceList);
        }

        //3.存入redis
        redisService.save(username, loginUserDetail, properties.getExpireTime(), TimeUnit.MINUTES);
        return Result.ok();
    }

    @Override
    public Result<String> register() {
        return Result.ok();
    }
}